package com.yyh.photo.utils;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

@Component
public class ImageUtils {

    /**
     * 接口调用凭证 access_token
     */
    public static String postToken() throws Exception {
        String appId = "wxb286c122bc060985";
        String appKey = "4d8de39b298af4237ffc7262c2b85d7f";
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appKey;
        URL url = new URL(requestUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes("");
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in;
        if (requestUrl.contains("nlp"))
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
        else
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        StringBuilder result = new StringBuilder();
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result.append(getLine);
        }
        in.close();
        JSONObject jsonObject = JSONObject.parseObject(result.toString());
        return jsonObject.getString("access_token");
    }


    /**
     * 生成微信小程序二维码
     *
     * @param filePath    本地生成二维码路径
     * @param page        当前小程序相对页面 必须是已经发布的小程序存在的页面（否则报错），例如 pages/index/index, 根路径前不要填加 /,不能携带参数（参数请放在scene字段里），如果不填写这个字段，默认跳主页面
     * @param scene       最大32个可见字符，只支持数字，大小写英文以及部分特殊字符：!#$&'()*+,/:;=?@-._~，其它字符请自行编码为合法字符（因不支持%，中文无法使用 urlencode 处理，请使用其他编码方式）
     * @param accessToken 接口调用凭证
     */
    public static void generateQrCode(String filePath, String page, String scene, String accessToken) {

        try {

            //调用微信接口生成二维码
            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            //这就是你二维码里携带的参数 String型  名称不可变
            paramJson.put("scene", scene);
            //注意该接口传入的是page而不是path
            paramJson.put("page", page);
            //这是设置扫描二维码后跳转的页面
            paramJson.put("width", 200);
            paramJson.put("is_hyaline", true);
            paramJson.put("auto_color", true);
            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();

            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            File file = new File(filePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            OutputStream os = new FileOutputStream(file);
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1) {
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 接口调用凭证 access_token
     */
    public static JSONObject getAccessToken(String code) throws Exception {
        String appId = "wxb286c122bc060985";
        String appKey = "4d8de39b298af4237ffc7262c2b85d7f";
//        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="+appKey+"&code="+code+"&grant_type=authorization_code";
        String rul = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appKey + "&js_code=" + code + "&grant_type=authorization_code";
//        String urlP = "https://qyapi.weixin.qq.com/cgi-bin/miniprogram/jscode2session?access_token="+token+"&js_code="+code+"&grant_type=authorization_code";
        URL url = new URL(rul);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes("");
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in;
        if (rul.contains("nlp"))
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
        else
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        StringBuilder result = new StringBuilder();
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result.append(getLine);
        }
        in.close();
        JSONObject jsonObject = JSONObject.parseObject(result.toString());
        return jsonObject;
    }

    /**
     * 接口调用凭证 access_token
     */
    public static JSONObject getUserInfo(String openId, String token) throws Exception {
        String appId = "wxb286c122bc060985";
        String appKey = "4d8de39b298af4237ffc7262c2b85d7f";
        String rul = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + token + "N&openid=" + openId + "&lang=zh_CN";
        URL url = new URL(rul);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.writeBytes("");
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in;
        if (rul.contains("nlp"))
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
        else
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        StringBuilder result = new StringBuilder();
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result.append(getLine);
        }
        in.close();
        JSONObject jsonObject = JSONObject.parseObject(result.toString());
        return jsonObject;
    }


    public static String getminiqrQr(String accessToken,  Integer width, String path) throws Exception {

        String p = "D://"; //二维码生产的地址 本地F盘code文件夹

        System.out.println(p);

        String codeUrl = p + "/twoCode.png";

        String twoCodeUrl = "twoCode.png";

        URL url = new URL("https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" + accessToken);

        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

        httpURLConnection.setRequestMethod("POST");// 提交模式

// conn.setConnectTimeout(10000);//连接超时 单位毫秒

// conn.setReadTimeout(2000);//读取超时 单位毫秒

// 发送POST请求必须设置如下两行

        httpURLConnection.setDoOutput(true);

        httpURLConnection.setDoInput(true);

        // 获取URLConnection对象对应的输出流

        PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());

        // 发送请求参数

        JSONObject paramJson = new JSONObject();

//      paramJson.put("scene","2");//这就是你二维码里携带的参数 String型 名称不可变

        paramJson.put("path", path); //这是设置扫描二维码后跳转的页面

        paramJson.put("width", width);

//      paramJson.put("is_hyaline", true);

//      paramJson.put("auto_color", true);

        System.out.println("httpURLConnection" + httpURLConnection);

        System.out.println("paramJson.toString()" + paramJson.toString());

        printWriter.write(paramJson.toString());

        // flush输出流的缓冲

        printWriter.flush();

        //开始获取数据

        BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
        File file = new File(codeUrl);
        if(file.exists()){
            file.createNewFile();
        }
        OutputStream os = new FileOutputStream(new File(codeUrl));

        int len;

        byte[] arr = new byte[1024];

        while ((len = bis.read(arr)) != -1) {

            os.write(arr, 0, len);

            os.flush();

        }

        os.flush();

        os.close();

//        response.setContentType("image/png");
//
//        response.setHeader("Pragma", "no-cache");
//
//        response.setHeader("Cache-Control", "no-cache");
//
//        response.setDateHeader("Expires", 0);
//
//        OutputStream stream = response.getOutputStream();
//
//        byte[] arr1 = new byte[1024];
//
//        while ((len = bis.read(arr1)) != -1) {
//
//            stream.write(arr1, 0, len);
//
//            stream.flush();
//
//        }
//
//        stream.flush();
//
//        stream.close();

        return twoCodeUrl;

    }

    public static void main(String[] args) {
        try {
            String token = postToken();
            System.out.println(getminiqrQr(token,100, "page/home/home"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
